package com.jandan.ui.client;

import java.util.Date;
import java.util.Iterator;
import java.util.List;

import com.allen_sauer.gwt.voices.client.Sound;
import com.allen_sauer.gwt.voices.client.SoundController;
import com.allen_sauer.gwt.voices.client.handler.PlaybackCompleteEvent;
import com.allen_sauer.gwt.voices.client.handler.SoundHandler;
import com.allen_sauer.gwt.voices.client.handler.SoundLoadStateChangeEvent;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.Hyperlink;
import com.google.gwt.user.client.ui.Widget;
import com.gwtext.client.core.EventObject;
import com.gwtext.client.widgets.Button;
import com.gwtext.client.widgets.MessageBox;
import com.gwtext.client.widgets.Panel;
import com.gwtext.client.widgets.event.ButtonListenerAdapter;
import com.gwtext.client.widgets.form.Label;
import com.gwtext.client.widgets.form.TextArea;
import com.gwtext.client.widgets.layout.HorizontalLayout;
import com.gwtext.client.widgets.layout.VerticalLayout;
import com.jandan.ui.client.service.WordCommentService;
import com.jandan.ui.client.service.WordCommentServiceAsync;
import com.jandan.ui.client.service.WordLibService;
import com.jandan.ui.client.service.WordLibServiceAsync;
import com.jandan.ui.model.CnAndSentence;
import com.jandan.ui.model.Word;
import com.jandan.ui.model.WordComment;

public class WordPanel extends Panel {
	private Word word;
	private Panel wordInfoPanel;
	private Panel commentsPanel;
	private Panel newCommentPanel;

	public WordPanel(Word word) {
		this.word = word;

		createComponent();
	}

	private void createComponent() {
		this.setLayout(new VerticalLayout(20));

		wordInfoPanel = new Panel();
		wordInfoPanel.setPaddings(10, 20, 0, 0);
		wordInfoPanel.setWidth(400);
		wordInfoPanel.setBorder(false);

		Panel wordEnPanel = new Panel();
		wordEnPanel.setLayout(new HorizontalLayout(10));
		Label wordEnLabel = new Label(word.getWordEn());
		wordEnLabel.addClass("word-label");
		wordEnPanel.add(wordEnLabel);

		Panel imagePanel = new Panel();
		imagePanel.setLayout(new HorizontalLayout(2));
		Hyperlink pronouceLink = new Hyperlink("发音", true, "");
		pronouceLink.addClickListener(new ClickListener() {

			public void onClick(Widget sender) {
				// TODO Auto-generated method stub
				SoundController soundController = new SoundController();
				String w = word.getWordEn();

				// create a sound
				final Sound sound = soundController.createSound(
						Sound.MIME_TYPE_AUDIO_MPEG, "mp3/" + w + ".mp3");

				// add a sound handler so we know when the sound has loaded
				sound.addEventHandler(new SoundHandler() {

					public void onPlaybackComplete(PlaybackCompleteEvent event) {
						// WARNING: this method may in fact never be called; see
						// Sound.LoadState
					}

					public void onSoundLoadStateChange(
							SoundLoadStateChangeEvent event) {
						// See detailed documentation in Sound.LoadState
						// in order to understand these possible values:
						// LOAD_STATE_SUPPORTED_AND_READY
						// LOAD_STATE_SUPPORTED_NOT_READY
						// LOAD_STATE_SUPPORTED_MAYBE_READY
						// LOAD_STATE_NOT_SUPPORTED
						// LOAD_STATE_SUPPORT_NOT_KNOWN
						// LOAD_STATE_UNINITIALIZED
					}
				});
				sound.play();
			}
		});

		imagePanel.add(pronouceLink);

		Hyperlink addStrangeWordLink = new Hyperlink("添加生词", true, "");
		addStrangeWordLink.addClickListener(new ClickListener() {

			public void onClick(Widget sender) {
				// TODO Auto-generated method stub
				WordLibServiceAsync wordLibService = WordLibService.Util
						.getInstance();

				wordLibService.addStrangeWord(word, new AsyncCallback() {

					public void onFailure(Throwable caught) {
						// TODO Auto-generated method stub
						MessageBox.alert("添加生词错误");
					}

					public void onSuccess(Object result) {
						// TODO Auto-generated method stub
						MessageBox.alert("add strange word successfully");
					}
				});
			}
		});
		imagePanel.add(addStrangeWordLink);

		wordEnPanel.add(imagePanel);
		wordInfoPanel.add(wordEnPanel);

		Panel pcnsPanel = new Panel();
		pcnsPanel.setHtml(getWordInfo());
		pcnsPanel.setBorder(false);
		wordInfoPanel.add(pcnsPanel);
		this.add(wordInfoPanel);

		commentsPanel = new Panel();
		commentsPanel.setPaddings(10, 20, 0, 0);
		commentsPanel.setWidth(400);
		commentsPanel.setBorder(false);
		showCommentInfo();
		this.add(commentsPanel);

		newCommentPanel = new Panel();
		newCommentPanel.setLayout(new VerticalLayout(10));
		newCommentPanel.setPaddings(10, 20, 0, 0);
		newCommentPanel.setWidth(400);
		newCommentPanel.setBorder(false);

		Label label = new Label("发表评论:");
		label.addClass("comment-label");
		final TextArea commentArea = new TextArea();
		commentArea.setWidth(350);
		commentArea.setHeight(100);
		commentArea.setName("newcomment");

		newCommentPanel.add(label);
		newCommentPanel.add(commentArea);

		final Button sentButton = new Button("发送");
		sentButton.addListener(new ButtonListenerAdapter() {
			@Override
			public void onClick(Button button, EventObject e) {
				// TODO Auto-generated method stub
				if (commentArea.getText() != null
						&& commentArea.getText().trim().length() > 0) {

					WordComment wordComment = new WordComment();
					wordComment.setContent(commentArea.getText());
					wordComment.setWordID(word.getWordID());
					wordComment.setCreatedDate(new Date());

					addWordComment(wordComment);
				}
				else {
					MessageBox.alert("评论内容不能为空");
				}
			}
		});

		newCommentPanel.add(sentButton);

		this.add(newCommentPanel);
	}

	private String getWordInfo() {
		StringBuffer sb = new StringBuffer("<p><span class='phonetics'>");
		sb.append(word.getPhonetics());
		sb.append("</span><br/><br/>");;

		List<CnAndSentence> cnAndSentenceList = word.getCnAndSentenceList();
		if (cnAndSentenceList != null) {
			CnAndSentence cs = null;
			String c = null;
			String s = null;
			for (int i = 0, n = cnAndSentenceList.size(); i < n; i++) {
				cs = cnAndSentenceList.get(i);
				c = cs.getCn();
				s = cs.getSentence();

				sb.append("<div class='cns'>");
				sb.append("<span class='cn'>");
				sb.append(c);
				sb.append("</span><br/><span class='cs'>");
				sb.append(s);
				sb.append("</span></div><br/></p>");
			}
		}
		return sb.toString();
	}

	private String getCommentsInfo(List<WordComment> commentList) {
		DateTimeFormat fmt = DateTimeFormat.getFormat("yyyy-MM-dd HH:mm:ss");
		StringBuilder sb = new StringBuilder();
		sb.append("<div>");
		Iterator<WordComment> it = commentList.iterator();
		WordComment wc = null;
		while (it.hasNext()) {
			wc = it.next();
			sb.append("<div class='comment'>");
			sb.append("用户名：<span class='username'>" + wc.getUserName()
					+ "</span>");
			sb.append("<span class='date'>发表日期:");
			sb.append(fmt.format(wc.getCreatedDate()));
			sb.append("</span>");
			sb.append("<div class='content'><p>" + wc.getContent()
					+ "</p></div>");
			sb.append("</div>");
		}

		sb.append("</div>");

		return sb.toString();
	}

	private void showCommentInfo() {
		WordCommentServiceAsync wordCommentService = WordCommentService.Util
				.getInstance();
		wordCommentService.getWordCommentListByWordID(word.getWordID(),
				new AsyncCallback<List<WordComment>>() {

					public void onFailure(Throwable caught) {
						// TODO Auto-generated method stub
						MessageBox.alert("获取评论错误");
					}

					public void onSuccess(List<WordComment> result) {
						// TODO Auto-generated method stub
						if (result != null && result.size() > 0) {
							commentsPanel.setHtml(getCommentsInfo(result));
						}
					}
				});
	}

	private void addWordComment(WordComment wordComment) {
		WordCommentServiceAsync wordCommentService = WordCommentService.Util
				.getInstance();
		wordCommentService.addWordComment(wordComment,
				new AsyncCallback<WordComment>() {

					public void onFailure(Throwable caught) {
						// TODO Auto-generated method stub
						MessageBox.alert("添加评论错误");
					}

					public void onSuccess(WordComment result) {
						// TODO Auto-generated method stub
						showCommentInfo();
					}
				});
	}

}
